// 全局变量
let allHistoryData = [];
let filteredHistoryData = [];
let currentFilters = {
    username: '',
    startDate: '',
    endDate: ''
};
let currentPage = 1;
let perPage = 10;
let totalPages = 1;
let totalRecords = 0;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadHistoryData();
    setupEventListeners();
    setDefaultDates();
});

// 设置事件监听器
function setupEventListeners() {
    // 用户名输入框回车事件
    const usernameFilter = document.getElementById('username-filter');
    if (usernameFilter) {
        usernameFilter.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                applyFilters();
            }
        });
    }
}

// 设置默认日期范围（最近7天）
function setDefaultDates() {
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 7);
    
    document.getElementById('end-date').value = endDate.toISOString().split('T')[0];
    document.getElementById('start-date').value = startDate.toISOString().split('T')[0];
}

// 加载历史数据
async function loadHistoryData(page = currentPage, per_page = perPage) {
    try {
        const filters = getCurrentFilters();
        const queryParams = new URLSearchParams();
        if (filters.username) queryParams.append('username', filters.username);
        if (filters.startDate) queryParams.append('start_date', filters.startDate);
        if (filters.endDate) queryParams.append('end_date', filters.endDate);
        queryParams.append('page', page);
        queryParams.append('per_page', per_page);
        const response = await fetch(`/api/connection-history?${queryParams.toString()}`);
        const result = await response.json();
        if (response.ok) {
            // result: {total, total_pages, page, per_page, data}
            allHistoryData = result.data;
            currentPage = result.page;
            perPage = result.per_page;
            totalPages = result.total_pages;
            totalRecords = result.total;
            updateHistoryTable(allHistoryData);
            updateRecordCount(totalRecords);
            updatePaginationControls();
            // 加载统计信息
            await loadStats();
            // 如果指定了用户名，加载用户统计
            if (filters.username) {
                await loadUserStats(filters.username);
            } else {
                hideUserStats();
            }
        } else {
            console.error('加载数据失败:', result.error);
            showTableError('加载数据失败: ' + result.error);
        }
    } catch (error) {
        console.error('网络错误:', error);
        showTableError('网络连接错误，请检查服务器状态');
    }
}

// 获取当前过滤条件
function getCurrentFilters() {
    return {
        username: document.getElementById('username-filter').value.trim(),
        startDate: document.getElementById('start-date').value,
        endDate: document.getElementById('end-date').value
    };
}

// 应用过滤条件
async function applyFilters() {
    currentFilters = getCurrentFilters();
    currentPage = 1;
    await loadHistoryData(currentPage, perPage);
}

// 清空过滤条件
async function clearFilters() {
    document.getElementById('username-filter').value = '';
    document.getElementById('start-date').value = '';
    document.getElementById('end-date').value = '';
    
    currentFilters = {
        username: '',
        startDate: '',
        endDate: ''
    };
    currentPage = 1;
    await loadHistoryData(currentPage, perPage);
}

// 加载统计信息
async function loadStats() {
    try {
        const filters = getCurrentFilters();
        const queryParams = new URLSearchParams();
        
        if (filters.username) queryParams.append('username', filters.username);
        if (filters.startDate) queryParams.append('start_date', filters.startDate);
        if (filters.endDate) queryParams.append('end_date', filters.endDate);
        
        const response = await fetch(`/api/connection-stats?${queryParams.toString()}`);
        const stats = await response.json();
        
        if (response.ok) {
            updateHistoryStats(stats);
        } else {
            console.error('加载统计信息失败:', stats.error);
        }
    } catch (error) {
        console.error('加载统计信息错误:', error);
    }
}

// 加载用户统计信息
async function loadUserStats(username) {
    try {
        const filters = getCurrentFilters();
        const queryParams = new URLSearchParams();
        
        queryParams.append('username', username);
        if (filters.startDate) queryParams.append('start_date', filters.startDate);
        if (filters.endDate) queryParams.append('end_date', filters.endDate);
        
        const response = await fetch(`/api/user-stats?${queryParams.toString()}`);
        const userStats = await response.json();
        
        if (response.ok) {
            updateUserStats(userStats);
            showUserStats();
        } else {
            console.error('加载用户统计失败:', userStats.error);
            hideUserStats();
        }
    } catch (error) {
        console.error('加载用户统计错误:', error);
        hideUserStats();
    }
}

// 显示用户统计
function showUserStats() {
    const userStatsCard = document.getElementById('user-stats-card');
    if (userStatsCard) {
        userStatsCard.style.display = 'block';
    }
}

// 隐藏用户统计
function hideUserStats() {
    const userStatsCard = document.getElementById('user-stats-card');
    if (userStatsCard) {
        userStatsCard.style.display = 'none';
    }
}

// 更新用户统计信息
function updateUserStats(userStats) {
    document.getElementById('user-connections').textContent = userStats.total_connections;
    document.getElementById('user-total-duration').textContent = userStats.total_duration_formatted;
    document.getElementById('user-avg-duration').textContent = userStats.avg_duration_formatted;
    document.getElementById('user-total-received').textContent = userStats.total_received_formatted;
    document.getElementById('user-total-sent').textContent = userStats.total_sent_formatted;
    document.getElementById('user-total-traffic').textContent = userStats.total_traffic_formatted;
}

// 更新历史记录表格
function updateHistoryTable(history) {
    const tbody = document.getElementById('history-table');
    
    if (history.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="8" class="empty-state">
                    <i class="fas fa-history"></i>
                    <h3>暂无历史记录</h3>
                    <p>没有找到符合条件的连接历史记录</p>
                </td>
            </tr>
        `;
        return;
    }
    
    const rowsHTML = history.map(record => createHistoryTableRow(record)).join('');
    tbody.innerHTML = rowsHTML;
}

// 创建历史记录表格行
function createHistoryTableRow(record) {
    const connectedTime = record.connected_since ? new Date(record.connected_since).toLocaleString('zh-CN') : '未知';
    const disconnectedTime = record.disconnected_at ? new Date(record.disconnected_at).toLocaleString('zh-CN') : '未知';
    const location = record.location || '未知地区';
    
    return `
        <tr>
            <td>
                <div class="user-cell">
                    <div class="user-avatar-small">
                        ${record.username.charAt(0).toUpperCase()}
                    </div>
                    <span class="username">${record.username}</span>
                </div>
            </td>
            <td><code class="ip-address">${record.virtual_address}</code></td>
            <td class="location-cell">
                <i class="fas fa-map-marker-alt"></i>
                <span class="location-text">${location}</span>
            </td>
            <td class="traffic-cell download">
                <i class="fas fa-download"></i>
                ${record.traffic_received}
            </td>
            <td class="traffic-cell upload">
                <i class="fas fa-upload"></i>
                ${record.traffic_sent}
            </td>
            <td class="duration-cell">
                <i class="fas fa-clock"></i>
                ${record.duration_formatted}
            </td>
            <td>${connectedTime}</td>
            <td>${disconnectedTime}</td>
        </tr>
    `;
}

// 更新历史统计信息
function updateHistoryStats(stats) {
    document.getElementById('total-users').textContent = stats.unique_users;
    document.getElementById('total-connections').textContent = stats.total_connections;
    document.getElementById('avg-duration').textContent = stats.avg_duration_formatted;
    document.getElementById('total-traffic').textContent = stats.total_traffic_formatted;
}

// 更新记录计数
function updateRecordCount(count) {
    const countElement = document.getElementById('record-count');
    if (countElement) {
        countElement.textContent = `${count} 条记录`;
    }
}

// 刷新历史数据
function refreshHistory() {
    currentPage = 1;
    loadHistoryData(currentPage, perPage);
}

// 格式化字节数
function formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示表格错误信息
function showTableError(message) {
    const tbody = document.getElementById('history-table');
    tbody.innerHTML = `
        <tr>
            <td colspan="8" class="error-state">
                <i class="fas fa-exclamation-triangle"></i>
                <h3>加载失败</h3>
                <p>${message}</p>
                <button class="refresh-btn" onclick="refreshHistory()">
                    <i class="fas fa-sync-alt"></i> 重试
                </button>
            </td>
        </tr>
    `;
    
    updateRecordCount(0);
}

// 添加额外的CSS样式
const additionalStyles = `
    .filter-form {
        padding: 20px 0;
    }
    
    .filter-row {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        align-items: end;
    }
    
    .filter-group {
        display: flex;
        flex-direction: column;
        gap: 8px;
        min-width: 200px;
    }
    
    .filter-group label {
        font-weight: 600;
        color: #2d3748;
        font-size: 14px;
    }
    
    .filter-group input {
        padding: 12px 16px;
        border: 2px solid rgba(102, 126, 234, 0.2);
        border-radius: 8px;
        font-size: 14px;
        background: white;
        transition: all 0.3s ease;
    }
    
    .filter-group input:focus {
        outline: none;
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
    
    .filter-actions {
        display: flex;
        gap: 10px;
        align-items: end;
    }
    
    .btn {
        padding: 12px 24px;
        border: none;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }
    
    .btn-secondary {
        background: #e2e8f0;
        color: #4a5568;
    }
    
    .btn-secondary:hover {
        background: #cbd5e0;
        transform: translateY(-2px);
    }
    
    .user-stats {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        padding: 20px 0;
    }
    
    .user-cell {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .user-avatar-small {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 14px;
        font-weight: 600;
    }
    
    .username {
        font-weight: 600;
        color: #2d3748;
    }
    
    .ip-address {
        background: rgba(102, 126, 234, 0.1);
        padding: 4px 8px;
        border-radius: 6px;
        font-family: 'Courier New', monospace;
        font-size: 12px;
        color: #667eea;
        white-space: nowrap;
    }
    
    .location-cell {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #805ad5;
        font-weight: 600;
        white-space: nowrap;
    }
    
    .location-text {
        font-size: 12px;
    }
    
    .traffic-cell {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 600;
    }
    
    .traffic-cell.download {
        color: #38a169;
    }
    
    .traffic-cell.upload {
        color: #dd6b20;
    }
    
    .duration-cell {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #667eea;
        font-weight: 600;
    }
    
    .empty-state, .error-state {
        text-align: center;
        padding: 40px;
        color: #718096;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 15px;
    }
    
    .empty-state i, .error-state i {
        font-size: 24px;
        color: #667eea;
    }
    
    .empty-state h3, .error-state h3 {
        color: #2d3748;
        margin: 0;
    }
    
    .empty-state p, .error-state p {
        margin: 0;
        color: #718096;
    }
    
    @media (max-width: 768px) {
        .filter-row {
            flex-direction: column;
            align-items: stretch;
        }
        
        .filter-group {
            min-width: auto;
        }
        
        .filter-actions {
            justify-content: center;
        }
        
        .user-stats {
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        }
    }
    
    /* 分页控件样式 */
    .pagination-container {
        background: white;
        border-radius: 12px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        margin: 20px 0;
        padding: 20px;
        border: 1px solid #e2e8f0;
    }
    
    .pagination-controls {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 15px;
        flex-wrap: wrap;
    }
    
    .pagination-controls button {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        padding: 10px 16px;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        gap: 8px;
        min-width: 100px;
        justify-content: center;
    }
    
    .pagination-controls button:hover:not(:disabled) {
        background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    }
    
    .pagination-controls button:disabled {
        background: #cbd5e0;
        color: #a0aec0;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
    }
    
    .pagination-controls button:active:not(:disabled) {
        transform: translateY(0);
    }
    
    #pagination-info {
        background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
        padding: 10px 20px;
        border-radius: 8px;
        font-weight: 600;
        color: #2d3748;
        border: 1px solid #e2e8f0;
        min-width: 120px;
        text-align: center;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }
    
    .per-page-label {
        font-weight: 600;
        color: #4a5568;
        margin-right: 8px;
    }
    
    #per-page-select {
        background: white;
        border: 2px solid #e2e8f0;
        border-radius: 8px;
        padding: 8px 12px;
        font-weight: 600;
        color: #2d3748;
        cursor: pointer;
        transition: all 0.3s ease;
        min-width: 80px;
    }
    
    #per-page-select:hover {
        border-color: #667eea;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
    }
    
    #per-page-select:focus {
        outline: none;
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
    
    .pagination-controls span:last-child {
        font-weight: 600;
        color: #4a5568;
    }
    
    @media (max-width: 768px) {
        .pagination-controls {
            flex-direction: column;
            gap: 10px;
        }
        
        .pagination-controls button {
            min-width: 120px;
        }
        
        #pagination-info {
            min-width: 100px;
        }
    }
`;

// 动态添加样式
const styleSheet = document.createElement('style');
styleSheet.textContent = additionalStyles;
document.head.appendChild(styleSheet);

// 分页控件相关
function updatePaginationControls() {
    document.getElementById('pagination-info').textContent = `第 ${currentPage} / ${totalPages} 页`;
    document.getElementById('prev-page').disabled = currentPage <= 1;
    document.getElementById('next-page').disabled = currentPage >= totalPages;
    document.getElementById('per-page-select').value = perPage;
}

function changePage(delta) {
    if ((delta < 0 && currentPage > 1) || (delta > 0 && currentPage < totalPages)) {
        currentPage += delta;
        loadHistoryData(currentPage, perPage);
    }
}

function changePerPage() {
    const select = document.getElementById('per-page-select');
    perPage = parseInt(select.value);
    currentPage = 1;
    loadHistoryData(currentPage, perPage);
} 